#! /usr/bin/env python
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from sinawb import mdb
from rpcclient import rpcclient 
import time
debug=True
def dp(*data):
     """
     this function work the same as print()
     """
     if debug:
         if len(data)==1:
             print data
         else:
     for d in data:
         print d
 
 
def getDate():
     """
     return today's 00:00:00 unix time which format like time.time()
     """
     today=time.localtime()
     year=today.tm_year
     month=today.tm_mon
     day=today.tm_mday
     init_date_tuple=(year,month,day,0,10,10,10,0,0)
     unixTime=time.mktime(init_date_tuple)
     return unixTime

def getPic(request):
     dp( "request.GET:",request.GET)
     keyword=request.GET.get('kword',None)
     dp("keyword:%s"%keyword,type(keyword))
     result=u"""
     <html>
         <head> 
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
         </head>
         <body>
             <div align="center" >
                 <h1>微博关键词趋势<h1>
 d               <img src ="%s" width="1000px" height="340px" >
                 </img>
                 <form action="/search" method="get">
                   <p>关键词: <input type="text" name="kword" id="kword" /></p>
                   <button type="submit">go</button>
                 </form>
             <div>
         </body>
     </html>
     """
     if keyword:
        keyword=keyword.encode('utf-8')
        pic_url=mdb.pic.find_one({'keyword':keyword})
        mdb.keyword_insert(keyword)
        if pic_url and pic_url['lastupdate']>(getDate()+7200):
            dp('================Have pic in db======================')
            chat=pic_url['url']
        else:
            dp('================no pic in db,calculating ======================')
            chat=rpcclient(keyword,10)
            print 'chat type:',type(chat)
            mdb.pic_update(keyword,chat.encode('utf-8'))
        print 'chat:',chat
        result=result%chat
#            print str(result)
        return HttpResponse(result)
    else:
        return HttpResponse("invalid keyword")
def mainpage(request):
    result="""
    <html>
        <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
        </head>
        
        <body>
            <div align="center" >
                <form action="/search" method="get">
                  <p>keyword: <input type="text" name="kword" id="kword" /></p>
                  <button type="submit">go</button>
                </form>
            <div>
        </body>
    </html>
    """
    return HttpResponse(result)
